package antonst.dcl;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Locale;

import javax.tools.*;
import javax.tools.JavaCompiler.CompilationTask;

class CustomCompiller {

	public void recompile(Iterable<? extends File> files) {
		JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
		StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, Locale.getDefault(), null);
		Iterable<? extends JavaFileObject> compilationUnits = fileManager
				.getJavaFileObjectsFromFiles(files);
		String classpath = getClass().getClassLoader().getResource("").getPath();
		String[] compileOptions = new String[] { "-d", classpath };
		Iterable<String> compilationOptions = Arrays.asList(compileOptions);
		DiagnosticCollector<JavaFileObject> diagnosticListener = new DiagnosticCollector<JavaFileObject>();
		CompilationTask task = compiler.getTask(null, fileManager,
				diagnosticListener, compilationOptions, null, compilationUnits);
		boolean status = task.call();
		if (!status) {// If compilation error occurs
			/* Iterate through each compilation problem and print it */
			for (Diagnostic diagnostic : diagnosticListener.getDiagnostics()) {
				System.out.format("Error on line %d in %s",
						diagnostic.getLineNumber(), diagnostic);
			}
		}
		try {
			fileManager.close();// Close the file manager
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
